<?php

class Core_Backend_Component_Foundation_Controller_Catalogue extends Dcmp_Component_Controller {

    public function indexAction($pageindex = 1, $pagesize = 20, $sort = 'id', $dir = 'asc') {
        $this->getHistory()->record();
        $list = App::getModel('foundation/collection_catalogue')
                    ->pagination($pageindex, $pagesize)
                    ->sortBy($sort, $dir)
                    ->load();
        $records = $list->loadCount();
        return $this->viewResult(array('list' => $list, 'records' => $records));
    }

    public function createAction() {
        $parents = App::getModel('foundation/collection_catalogue')
                    ->joinRelation()
                    ->resetSelect()
                    ->fields('a.id', 'a.code', 'a.name', 'b.parent_code')
                    ->distinct()
                    ->load();
        return $this->viewResult(array('parents' => $parents));
    }

    public function editAction($id) {
        $model = App::getModel('foundation/catalogue')->load($id);
        $result = $this->createAction();
        $result->getParents()->removeItemById($model->getId());
        return $result->setModel($model);
    }

    public function applyPostAction() {
        return $this->saveModel(FALSE);
    }

    public function savePostAction() {
        return $this->saveModel();
    }

    private function saveModel($return = TRUE) {
        $data = $this->getRequest()->getForm('catalogue');
        $model = App::getModel('foundation/catalogue');
        if (isset($data['id']) && !empty($data['id'])) {
            $model->load($data['id']);
        }
        $model->addData($data);
        if (($errors = $model->validate() === TRUE)) {
            $model->save();
            $this->getMessager()->addInform($this->__f('share.message.saveSuccess', '{foundation.label.catalogue}', $model->getName()));
            return $return?
                    $this->redirectResult($this->getHistoryUrl('foundation/catalogue/index')):
                    $this->redirectResult($this->getUrl(array('id' => $model->getIdValue()), 'edit'));
        } else {
            $this->getMessager()->addError($this->__f('share.message.saveFail', '{foundation.label.catalogue}', $model->getName()))
                    ->addError($errors);
            return $this->createAction()->setModel($model);
        }
    }

}